package com.JobFind.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于检测用户是否登陆的过滤器，如果未登录或超时，则重定向到指的登录页面
 * 
 */
public class SessionFilterUtil implements Filter {

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;//将请求转化成HttpServletResponse 
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String currentURL = request.getRequestURI(); // 取得根目录所对应的绝对路径
		String checkURL = currentURL.substring(currentURL.lastIndexOf("/"), currentURL.length());
		HttpSession session = request.getSession(false);
		String type = request.getHeader("X-Requested-With");
		try {
			if (!"/loginCheck.action".equals(checkURL) && !"/regCheck.action".equals(checkURL)) {
				// 判断当前页是否是重定向以后的登录页面页面，如果是就不做session的判断，防止出现死循环
				if (session == null || session.getAttribute("loginusersession") == null) {
						response.sendRedirect("../user_login.html");
						return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		filterChain.doFilter(request, response);
	}

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}
}